package 力扣_树算法.遍历.层序遍历扩展;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/** 二叉树的层平均值
 * @author zx
 * @create 2022-04-09 18:36
 */
public class 二叉树的层平均值_637 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelCount = queue.size();
            double sum = 0;
            double number = 0;
            for(int i = 0;i < levelCount;i++){
                TreeNode node = queue.poll();
                sum += node.val;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                number = sum / levelCount;
            }
            res.add(number);
        }
        return res;
    }
}
